/*=============jQuery plugin/ Object function===============*/
jQuery.fn.isExist = function () {
    return jQuery(this).length > 0;
};

jQuery.fn.isNullOrEmpty = function () {
    if (jQuery(this).val() === null || $.trim(jQuery(this).val()) === "") {
        return true;
    } else {
        return false;
    }
};

String.prototype.isEmail = function () {
    var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(this);
};

jQuery.fn.stringIsValidate = function (minleng, maxlenth) {
    if (jQuery.trim(jQuery(this).val()).length < minleng || jQuery.trim(jQuery(this).val()).length > maxlenth) {
        jQuery(this).focus();
        return false;
    } else {
        return true;
    }
};


String.prototype.replaceAll = function (
        strTarget, // The substring you want to replace
        strSubString // The string you want to replace in.
        ) {
    var strText = this;
    var intIndexOfMatch = strText.indexOf(strTarget);
    while (intIndexOfMatch !== -1) {
        strText = strText.replace(strTarget, strSubString)
        intIndexOfMatch = strText.indexOf(strTarget);
    }
    return(strText);
};

function CurrencyFormatted(n) {
    return (Math.round(n * 100) / 100).toLocaleString();
}

String.prototype.subString = function (len) {
    if (this.length >= len) {
        return this.substring(0, len) + "...";
    }
    return this;
};

String.prototype.addslashes = function () {
    var str = this;
    str = str.replace(/\\/g, '\\\\');
    str = str.replace(/\'/g, '\\\'');
    str = str.replace(/\"/g, '\\"');
    str = str.replace(/\0/g, '\\0');
    return str;
};

String.prototype.stripslashes = function () {
    var str = this;
    str = str.replace(/\\'/g, '\'');
    str = str.replace(/\\"/g, '"');
    str = str.replace(/\\0/g, '\0');
    str = str.replace(/\\\\/g, '\\');
    return str;
};

/*==UI_Page Class==========================================================================*/

var UI_Page = function () {

    this.appName = "vtvnow";

    this.Base_Url = "";

    this.Base_Api = "";

    this.Base_Upload = "";

    this.setAppVersion = {};

    this.appVersion = function () {
        if (this.appOs == "ios") {
            return this.setAppVersion.ios;
        } else if (this.appOs == "android") {
            return this.setAppVersion.android;
        }
    };

    this.LAYOUT = "";

    this.isBack = false;

    this.onLoad = function (fn) {
        fn();
    };

    this.widgetLoad = function (fn) {
        fn();
    };

    this.onInit = function () {
        var url_target = window.location.hash.replace(/#|.html|tab-/g, "", "");

        var index = url_target.indexOf("?");
        if (index > 0) {
            url_target = url_target.substring(0, parseInt(index));
        }

        if (url_target !== "") {
            this.LAYOUT = "#page_" + url_target.replaceAll("/", "");
            $(this.LAYOUT).onLoadUrl("app/" + url_target + ".html");

        } else {
            this.LAYOUT = "#page_indexhome";
            $(this.LAYOUT).onLoadUrl("app/index/home.html");
        }
    };

    this.getParam = function (name) {
        var url = window.location.hash;
        var index = url.indexOf("?");
        var maxlen = url.length;

        if (index > 0) {//Kiem tra co param
            //Xu ly chuoi lan 1
            url = url.substring(index + 1, maxlen);
            var param_index = url.indexOf(name);
            if (param_index >= 0) {//Kiem tra lan 2, ton tai param can tim
                url = url.substring(param_index, maxlen);
                //Xu ly chuoi lan 2
                maxlen = url.indexOf("&") > 0 ? url.indexOf("&") : maxlen;
                url = url.substring(0, maxlen).replace(name + "=", "");
            } else {
                url = "";
            }
        } else {
            url = "";
        }
        return url;
    };

    this.redirect = function (url_state) {
        window.location.href = "#" + url_state.replace(".html", "");
    };

    this.back = function () {
        window.history.back();
        this.isBack = true;
    };

    this.hideWaiting = function () {
        new Popup().hideWaiting();
    };

    this.selectorId = function (selector) {
        return $(this.LAYOUT + " #" + selector);
    };

    this.selectorClass = function (selector) {
        return $(this.LAYOUT + " ." + selector);
    };

    this.selector = function (selector) {
        return $(this.LAYOUT + " " + selector);
    };

    this.extend = function (obj1, obj2) {
        for (var key in obj2)
            if (obj2.hasOwnProperty(key))
                obj1[key] = obj2[key];
    };

    this.appLayoutBeforeLoad = function (fn) {
        fn();
    };

    $.fn.onLoadUrl = function (url) {
        var $this = $(this);
        //$(".page_active").html("");
        $(".page_active").removeClass("page_active").addClass("page_hide");
        $this.addClass("page_active").removeClass("page_hide");

        if ($this.is(":empty")) {
            $this.load(url);
        }
    };

    this.ajax = function (options) {
        var params = {
            type: "GET",
            url: "",
            data: "",
            timeout: "",
            success: function () {
            },
            error: function () {
            },
            beforeSend: ""
        };
        this.extend(params, options);

        var request = new XMLHttpRequest();

        if (typeof params.beforeSend == 'function') {
            request.onloadstart = function () {
                params.beforeSend();
            };
        }


        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    params.success(request.responseText);
                } else if (request.status != 0) {
                    var data = {status: request.status, responseText: request.responseText};
                    params.error(data);
                }
            }
        };

        request.ontimeout = function () {
            var data = {status: "timeout", responseText: "Request time out"};
            params.error(data);
        };


        if (typeof params.data == 'object') {
            var str = "";
            for (var i in a) {
                str += "&" + i + "=" + a[i];
            }
            params.data = "?" + str.substring(1) + "&_=" + this.Timestamp.getDateTimeMilliseconds();
        }

        request.open(params.type, params.url + params.data, true);

        if (params.timeout != "") {
            request.timeout = params.timeout;
        }

        request.send();
    };

    this.dateTime = function (options) {
        //Default return timestamp
        return Math.round((new Date()).getTime() / 1000);
    };

    this.Timestamp = {
        getDateTime: function () {
            return Math.round((new Date()).getTime() / 1000);
        },
        getDateTimeMilliseconds: function () {
            return new Date().getTime();
        }
    };

    this.storage = {
        get: function (name) {
            if (localStorage.getItem(_this.appName + "_" + name) == null) {
                return "";
            } else {
                return localStorage.getItem(_this.appName + "_" + name);
            }
        },
        set: function (name, value) {
            localStorage.setItem(_this.appName + "_" + name, value);
        },
        remove: function (name) {
            localStorage.removeItem(_this.appName + "_" + name);
        }
    };

    this.getImageFileName = function (url) {
        var arr = url.split("/");
        return arr[arr.length - 1];
    };


    this.appConfirmUpdate = function (success) {
        //Ajax update
        setTimeout(function () {
            $.ajax({
                url: _this.Base_Api + "get-new-version-os",
                success: function (data) {


                    var link = "", version = 0;
                    if (_this.appOs == "ios") {
                        link = data.link_ios;
                        version = data.ver_ios;
                    } else if (_this.appOs == "android") {
                        link = data.link_android;
                        version = data.ver_android;
                    } else if (_this.appOs == "windowphone") {
                        link = data.link_wp;
                        version = data.ver_wp;
                    }

                    if (version != undefined && _this.appVersion() != version) {
                        Dialog.showConfirm({
                            title: "Thông báo",
                            content: "VTV Now đã có phiên bản mới, hãy cập nhật để có được các tính năng mới",
                            buttons: [
                                {
                                    id: "Confirm_OK",
                                    text: "Đồng ý",
                                    type: "bold"
                                }
                            ],
                            effectIn: "ZoomIn_3",
                            effectOut: "ZoomOut_4",
                            event: function () {
                                $("#Confirm_OK").on("tap", function () {
                                    window.open(link);
                                    Dialog.close();
                                });
                            }
                        });

                    } else {
                        success();
                    }
                }
            });
        }, 5000);
    };

    this.soundEffect = function (filename) {
        var file = _this.appOs == "android" ? "/android_asset/www/" : "";
        var sound = new GvAudio(file + 'public/sound/' + filename + '.mp3', false);
        sound.play();
    };

    this.mobileDetect = function () {

        var checker = {
            iphone: navigator.userAgent.match(/(iPhone|iPod|iPad)/),
            blackberry: navigator.userAgent.match(/BlackBerry/),
            android: navigator.userAgent.match(/Android/),
            windowphone: navigator.userAgent.match(/Windows Phone/),
            moto: navigator.userAgent.match(/MOTOROLA/),
            Windows: navigator.userAgent.match(/IEMobile/),
            Nokia: navigator.userAgent.match(/Nokia/),
            opera: navigator.userAgent.match(/Opera Mini/)
        };
        if (checker.android) {
            return "android";
        } else if (checker.iphone) {
            return "ios";
        } else if (checker.windowphone) {
            return "windowphone";
        }
    };

    this.appOs = this.mobileDetect();

    this.loadJs = function (url, success, error) {
        $.ajax({
            url: url,
            dataType: "script",
            async: false, // <-- This is the key
            success: function () {
                if (typeof success == 'function') {
                    success();
                }
            },
            error: function () {
                if (typeof error == 'function') {
                    success();
                }
            }
        });
    };


};

var GvAudio = function (file, loop) {

    if (_this.appOs == "android") {
        var audio = new Media(file);
    } else {
        var audio = new Audio(file); // nhạc chương trình
        audio.loop = loop;
    }

    this.play = function () {
        if (audio != null)
            audio.play();
    };

    this.onended = function (callback) {
        if (_this.appOs == "android") {
            if (loop) {
                audio.successCallback = function () {
                    audio.play();
                    if (typeof callback == 'function')
                        callback();
                };
            } else {
                audio.successCallback = callback;
            }
        } else {
            audio.onended = callback;
        }
    };

    this.pause = function () {
        if (audio != null)
            audio.pause();
    };

    this.stop = function () {
        this.pause();
        audio = null;
    };
};


var _this = new UI_Page();

if (!history.popState) {
    $(function () {
        _this.onInit();
    });
}
window.onpopstate = function (event) {
    _this.onInit();
};